/*********************************************************************************
 *      Copyright:  (C) 2020 makun<1394987689@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  pipe.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(2020年03月18日)
 *         Author:  makun <1394987689@qq.com>
 *      ChangeLog:  1, Release initial version on "2020年03月18日 17时05分31秒"
 *                 
 ********************************************************************************/

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>

#define MSG_STR "hello child"
int main (int argc, char **argv)
{
    int     fd[2];
    int     rv;
    pid_t   pid;
    char    buf[512];
    int     wstatus;

    if(pipe(fd) < 0)
    {
        printf("create pipe failure: %s\n",strerror(errno));
        return -1;
    }
    printf("打印成功后的返回值\n");

    if( (pid=fork()) < 0)
    {
        printf("create fork failure %s\n",strerror(errno));
        return -2;
    }
    else if(pid ==0 )
    {
        close(fd[1]);//关闭子进程的写端

        memset(buf , 0, sizeof(buf));
        rv=read(fd[0],buf,sizeof(buf));//把读到的数据写入buf
        if( rv < 0)
        {
            printf("read from fd[0] failure %s\n",strerror(errno));
            return -3;
        }
        printf("read from fd[0] successfuly and read  %d bytes\n", rv);
        return 0; 

    }
        else if( pid > 0)
        {
            
        close(fd[0]);//关闭父进程的读端
        if( write(fd[1],MSG_STR,strlen(MSG_STR)) < 0)
        {
            printf("write fd[1] from MSG_STR failure%s\n", strerror(errno));
            return -4;
        }


        printf("parent start wait child process exit..\n");
        wait(&wstatus);
        return 0;
        }
} 

